$(function(){
	var UID = $('[data-role="uid"]').val();
	/*
	 * 行政地区选择器初始化
	 */
	for (var i = 0; i < BTREGION.length; i++) {
		var area = {id:BTREGION[i].id,name:BTREGION[i].cname,level:BTREGION[i].level,parentId:BTREGION[i].upid};
		BTREGION[i] = area;
	}

	/*
	$('.bs-chinese-region').on('changed.bs.chinese-region',function(e,areas){
		  //areas是已选择的地区数据，按先选择的在最前的方式排序。
		  $(this).attr('data-result',areas[areas.length-1]['id']);
	});
	*/

	var regionInitor = {
		regionTplStr: $('#region-choocer-tpl').html(),
		initRegionEle : function ($ele) {
			var $replacer = $(swig.render(this.regionTplStr,{locals:{id:Math.round(Math.random()*1000)}}));
			$replacer.find('.address').replaceWith($ele.clone().attr('data-toggle','dropdown').attr('data-result',$ele.val()));
			$ele.replaceWith($replacer);
			$replacer.chineseRegion('source',BTREGION);
			$replacer.on('changed.bs.chinese-region',function(e,areas){
				  //areas是已选择的地区数据，按先选择的在最前的方式排序。
				  $(this).attr('data-result',areas[areas.length-1]['id']);
			});
		}
	};

	$('input.address').each(function() {
		regionInitor.initRegionEle($(this));
	});

	function getComInfoObj($comBoxEle) {
		function getEleByDataRole(dataRole) {
			return $comBoxEle.find('[data-role="'+dataRole+'"]');
		}
		var result = {
			'com-id': $comBoxEle.attr('data-id'), 
			'logo-url': getEleByDataRole('logo-url').attr('data-url'),
			'com-name': getEleByDataRole('com-name').html(),
			'position': getEleByDataRole('position').html(),
			'addr-id': getEleByDataRole('addr-id').attr('data-result'),
			'addr-name': getEleByDataRole('addr-id').val(), 
			'industry-id': getEleByDataRole('industry-id').attr('data-id'),
			'website': getEleByDataRole('website').html(),
			'stock-code': getEleByDataRole('stock-code').html(),
			'com-intro': getEleByDataRole('com-intro').html(),
			'is-auth':getEleByDataRole('is-auth').val()
		}			
		return result;
	}

	function fillComEditModal(obj) {
		function getEleByDataRole(dataRole) {
			return $comInfoEditor.find('[data-role="'+dataRole+'"]');
		}
		for( var key in obj) {
			var value = obj[key];
			if( key == 'industry-id') {
				getEleByDataRole(key).children().removeAttr('selected');
				getEleByDataRole(key).children('[data-id="'+value+'"]').attr('selected','');
			} else if(key == 'addr-id') {
				getEleByDataRole(key).val(value).attr('data-result',value);	
			} else if(key == 'addr-name') {
				$comInfoEditor.find('.address').val(value);	
			} else if(key == 'logo-url') {
				getEleByDataRole(key).attr('src',value);	
				getEleByDataRole(key).siblings('input').val(value);	
			} else if(key == 'is-auth') {
				if(value==1){
					getEleByDataRole("com-name").attr('disabled',"true");	
					getEleByDataRole("position").attr('disabled',"true");	
				}else{
					getEleByDataRole("com-name").removeAttr('disabled');
					getEleByDataRole("position").removeAttr('disabled');
				}
			} else {
				getEleByDataRole(key).val(value);	
			}
		}
	}

	function fillComInfoBox() {
		var $this = $(this); 				
		function getEleByDataRole($ele,dataRole) {
			return $ele.find('[data-role="'+dataRole+'"]');
		}
		getEleByDataRole($this,'logo-url').css('background-image','url('+getEleByDataRole($comInfoEditor,'logo-url').attr('src')+')');
		getEleByDataRole($this,'logo-url').attr('data-url',getEleByDataRole($comInfoEditor,'logo-url').attr('src'));
		getEleByDataRole($this,'com-name').html(getEleByDataRole($comInfoEditor,'com-name').val());
		getEleByDataRole($this,'position').html(getEleByDataRole($comInfoEditor,'position').val());
		getEleByDataRole($this,'addr-id').val(getEleByDataRole($comInfoEditor,'addr-id').val());
		getEleByDataRole($this,'addr-id').attr('data-result',getEleByDataRole($comInfoEditor,'addr-id').attr('data-result'));
		getEleByDataRole($this,'industry-id').html(getEleByDataRole($comInfoEditor,'industry-id').find(':selected').html());
		getEleByDataRole($this,'industry-id').attr('data-id',getEleByDataRole($comInfoEditor,'industry-id').find(':selected').attr('data-id'));
		getEleByDataRole($this,'website').html(getEleByDataRole($comInfoEditor,'website').val());
		getEleByDataRole($this,'stock-code').html(getEleByDataRole($comInfoEditor,'stock-code').val());
		getEleByDataRole($this,'com-intro').html(getEleByDataRole($comInfoEditor,'com-intro').val());
	}
	
	/*
	 * 编辑标签
	 */	
	var $comInfoEditor = $('#cominfo-editor');
	var $tagsEditor = $('#tags-editor');
	$('#tags .edit-btn').on('click',function(){
		$tagsEditor.modal('show');
		console.log(tagOnPage.getData());
		tagsEditor.setData(tagOnPage.getData());
	});
		
	$('.select2').select2();
	$comInfoEditor.modal({
		show: false,
		backdrop: 'static'
	});

	$('#com-edit-form').validate({
		showErrors: function(errorMap,errorList) {
			if(errorList.length > 0) {
				var firstErr = errorList[0];
				var $errEle = $(firstErr.element);
				try{
					$errEle.tooltip('hide').tooltip('destroy').tooltip({
						title: firstErr.message
					}).tooltip('show');
				} catch(e) {
				}
			}
		}
	});

	/*
	 * 页面上显示的标签
	 */
	function TagsOnPage($ele) {
		this.$ele = $ele;
	}
	TagsOnPage.prototype = {
		consotructor: TagsOnPage,
		$ele: null,
		getData: function() {
			var result = {};
			this.$ele.find('[data-role]').each(function(){
				var curCotegory = [];
				$(this).children('span').each(function(){
					curCotegory.push($(this).html());
				});
				result[$(this).attr('data-role')] = curCotegory;
			});
			return result;
		},
		setData: function(obj) {
			this.$ele.find('[data-role]').each(function(){
				$(this).empty();
				var roleName = $(this).attr('data-role');
				var tagArr = obj[roleName];
				var $tplEle = roleName == 'find' ? $('<span class="label label-success"></span>') : $('<span class="label label-warning"></span>');
				for( var index in tagArr) {
					if(tagArr[index]!=""){
						$(this).append($tplEle.clone().html(tagArr[index]));
					}
						
				}
			});
		}
	}

	var tagOnPage = new TagsOnPage($('#tags'));

	/*
	 * 标签编辑弹窗
	 */
	function TagsEditor($ele) {
		this.$ele = $ele;
	}

	 TagsEditor.prototype = {
		consotructor: TagsEditor,
		$ele: null,
		getData: function() {
			var result = {
				interest: this.$ele.find('[data-role="interest"]').val(),
			   	skill: this.$ele.find('[data-role="skill"]').val(),
				find: $('#find-input').val().split(',')
			};
			return result;	
		},
		setData: function(obj) {
			var self = this;
			function resetSel() {
				self.$ele.find('select').each(function(){
					$(this).children().removeAttr('selected[data-role]');
				});
			}
			resetSel();
			for(var key in obj) {
				if(key == 'find') {
					var tagInput = this.$ele.find('[data-role="'+key+'"]>input');
					var findArr = obj[key];
					tagInput.tagsinput('removeAll');
					for(var index in findArr) {
						tagInput.tagsinput('add',findArr[index]);
					}
				} else {
					var $curSel = this.$ele.find('[data-role="'+key+'"]');
					$curSel.select2('destroy');
					var tagArr = obj[key];
					for(var index in tagArr) {
						$curSel.children('[data-tag="'+tagArr[index]+'"]').attr('selected','');
					}
					$curSel.select2();
				}
			}		
		}
	}

	var tagsEditor = new TagsEditor($('#tags-editor'));
	var flag = true;
	$('#tags-editor .save-btn').on('click',function(){
		var tagDatas = tagsEditor.getData();
		_data = {};
		_data['uid'] = UID;
		if(tagDatas['interest']!=null){
			_data['interest'] = tagDatas['interest'].toString();
		}else{
			_data['interest'] = "";
		}
		if(tagDatas['find']!=''){
			_data['find'] = tagDatas['find'].toString();
		}else{
			_data['find'] = "";
		}
		if(tagDatas['skill']!=null){
			_data['skilled'] = tagDatas['skill'].toString();
		}else{
			_data['skilled'] = "";
		}
		if(flag){
			flag = false;
			cAjax({
				url: '/cms/appUser/appUser/saveUserTag',
				data: _data,
				success: function(obj) {
					flag = true;
					tagOnPage.setData(tagDatas);
					$('#tags-editor').modal('hide');
					greeting({
						msg: '标签保存成功'
					});
			    }
			});
		}
	});

	$('.com-info-box .add-btn').on('click',function(){
		fillComEditModal({
			'com-id':'', 
			'logo-url': '',
			'com-name': '',
			'position': '',
			'addr-id': '',
			'addr-name': '', 
			'industry-id':'',
			'website': '',
			'stock-code':'',
			'com-intro': '' 
		});
		$comInfoEditor.find("input[name='com_name']").removeAttr("disabled");
		$comInfoEditor.find("input[name='position']").removeAttr("disabled");
		$comInfoEditor.modal('show');
	});

	$('.save-btn',$comInfoEditor).on('click',function(){
		if(!$('#com-edit-form').valid()) {
			return;
		}
		function drawComInfoBox(obj) {
			var com_id = obj["data"];
			if($comInfoEditor.$curComBox == null) {
				$('.com-info:eq(0)').attr('data-id',com_id);
				var newComInfoBox = $($('.com-info')[0]).parent().clone().removeAttr('style');	
				$comInfoEditor.$curComBox = newComInfoBox;
				$('.com-info-box .box-parent').append(newComInfoBox);
				newComInfoBox.fadeIn();
			}
			fillComInfoBox.call($comInfoEditor.$curComBox);	
			$comInfoEditor.$curComBox = null;
			$comInfoEditor.modal('hide');
		}
		var formData = {
			user_id: UID
		};
		$('[name]',$comInfoEditor).each(function(){
			var $this = $(this);
			var fieldName = $this.attr('name');
			if( fieldName == 'main_industry') {
				formData[fieldName] = $this.children(':selected').attr('data-id');  
			} else if($this.attr('name') == 'com_city') {
				formData[fieldName] = $this.parent().attr('data-result');  
			} else {
				formData[fieldName] = $this.val();
			}
		});
		if(formData['com_id'] == '') {
			delete formData['com_id'];
		}
		var URL_ADD = '/cms/appUser/appUser/addCompany',
			URL_UPDATE = '/cms/appUser/appUser/editCompany';
		cAjax({
			url: formData['com_id'] == undefined? URL_ADD:URL_UPDATE,
			data: formData,
			success: function(obj) {
				drawComInfoBox(obj);
				greeting({
					msg: '公司信息保存成功'
				});
			}
		});
	});

	$('.com-info-box').on('click','.expand-btn',function(){
		$(this).parents('.com-info').find('.info-lang').collapse('toggle');
		$(this).parent().find('a').toggle();
	});

	$('.com-info-box').on('click','.del-btn',function(){
		var comId = $(this).parents('.com-info').attr('data-id');
		var $comBoxEle = $(this).parents('.com-info').parent();
		actionConfirm({
			msg: '确定删除这个公司信息吗？',
			confirm: function(){
				cAjax({
					url: '/cms/appUser/appUser/delCompany',
					data: {
						user_id: UID,
						com_id: comId
					},
					success: function() {
						$comBoxEle.remove();
						greeting({
							msg: "已删除"
						});
					},
					error:function(obj){
						alerting({msg:obj.msg});
					}
				});	
			}
		});	
	});

	$('.com-info-box').on('click','.edit-btn',function(){
		var $this = $(this);
		var obj = getComInfoObj($this.parents('.com-info'));
		fillComEditModal(obj);
		$comInfoEditor.$curComBox = $this.parents('.com-info');
		$comInfoEditor.modal('show');
	});

	function handleUploadSuccess(obj) {
		var $this = this;
		var photoUrl = obj['data'];
		$this.siblings('.pic').css('background-image','url('+photoUrl+')');	
		$this.siblings('input:hidden').val(photoUrl);
		$this.parent().find('[download]').attr('href',photoUrl);
	}

	var uploader = new PicUploader({
		success: function(obj){
			handleUploadSuccess.call($curBtn,obj);
		}
	});

	$('.btn.upload').on('click',function(){
		uploader.start();
		$curBtn = $(this);
	});

	/*
	 * 上传公司logo
	 */
	var logoUploader = new PicUploader({
		success: function(obj) {
			$('.com-logo',$comInfoEditor).attr('src',obj['data']);			
			$('.com-logo',$comInfoEditor).siblings('input').val(obj['data']);
		}
	});

	$('#logo-upload-btn').on('click',function(){
		logoUploader.start();
	});

	$('#box-account .save-btn').on('click',function(){
		var account = $("#account").val();
		var country_code=$("#country_code").val();
		if(country_code==''){
			alerting({msg:"国家/地区不能为空！"});
			return false;	
		}
		
//		var reg = /^0?1[0|3|4|5|7|8][0-9]\d{8}$/;
		var reg=/^[0-9]*$/;//只校验是否为数字
		if(account==''||!reg.test(account)){
			alerting({msg:"登录账号不合法！"});
			return false;
		}
		validAccount(UID,account,1,country_code);
	});
	
	
	
	$("#conflict-modal").modal({
		show: false,
		backdrop: 'static'
	});
	
	function validAccount(UID,account,mode,country_code){
		cAjax({
			url:'/cms/appUser/appUser/validAccount',
			data:{'user_id':UID,'account':account,'mode':mode,'country_code':country_code},
			success:function(obj){
				if(obj.msg == 0){
					//普通冲突
					$('#conflict-info').html(" ");
					initConflict(obj.data);
					$('#conflict-modal').modal('show');
				}else if(obj.msg == 1){
					greeting({
						msg: '操作已完成',
						confirm:function(){
							window.location.href="/cms/appUser/appUser/list";
						}
					});
				}else if(obj.msg == 2){
					alerting({msg:"帐号未修改"});
				}else if(obj.msg == 3){
					greeting({msg:"欲修改手机号的用户在黑名单中,拒绝修改"});
				}else if(obj.msg == 5){
					alerting({msg:"帐号已存在!"});
				}else{
					greeting({msg:"其他错误"});
				}
				
			}
		});
	}
	
	$('#main-info .save-btn').on('click',function(){
		var formData = {};
		$('#main-info input[name]').each(function() {
			var $this = $(this);
			formData[$this.attr('name')] = $this.val();
		});
		formData['industry'] = $("#userIndustry","#main-info").val(); 
		formData['introduce'] = $("textarea[name='introduce']","#main-info").val(); 
		formData['city'] = $('#main-info .address').parent().attr('data-result'); 
		formData['user_id'] = UID;
		formData['gender'] = $("input[name='gender']:checked").val();
		
		console.log(formData);
		if(flag){
			flag = false;
			editUser(formData);
		}
		
	});
	function editUser(formData){
		cAjax({
			url: '/cms/appUser/appUser/editUser',
			data: formData,
			success: function() {
				greeting({
					msg: '用户基本信息保存成功',
					confirm:function(){
						window.location.reload();
					}
				});
			}
		});
	}
	
	function initConflict(obj){
		var user = JSON.parse(obj);
		$('#conflict-info').html(user.uname+" "+user.account+" "+user.base_rank_label+" "+user.from_became_user_label+" "+user.com_name+" "+user.position);
		$('#conflict-info2').html(user.user_id+" "+user.uname+" "+user.com_name+" "+user.position);
		if(user.base_rank < 400){
			if(user.uname == "" | user.com_name == "" | user.position == ""){
				$("input[name ='mode']:eq(1)").attr("disabled","");
			}
		}
		$('#newBecame').html(user.from_became_user_label);
	}

	
	$("#conflict-modal .sava-conflict").on('click',function(){
		var mode = $("input[name='mode']:checked").val();
		var account = $("#account").val();
		var country_code = $("#country_code").val();
		if(mode==undefined){
			alert("请选择");
		}else{
			validAccount(UID,account,mode,country_code);
		}
	});
	
	
	/** 
	 * 推荐人
	 * 邀请人
	 * 服务岛丁
	 */
	var searchUser = function(e){
		var $this = $(e);
		var seachWords = $this.val(); 
		var suggestTplStr = $('#searh-user-tpl').html();
		var $suggestContainer = $this.parent().next();
		var url = "";
		var _parse = false;
		if($this.attr('id')=="servicer_uname"){
			_url = "/cms/appUser/appUser/searchUserDing";
		}else{
			_url = "/base/api/searchUserByName";
		}
		cAjax({
			url: _url,
			data: {
				keywords: seachWords
			},
			success: function(obj) {
				var items = obj["data"];
				$suggestContainer.empty();
				if(items.length == 0){
					$suggestContainer.append("没有结果...");
				}
				for(var index in items) {
					var data = items[index];
					var $itemEle = $(swig.render(suggestTplStr,{locals:{item:data}}));
					$suggestContainer.append($itemEle);		
				}
			}
		});
	}
	
	$("input.search-user").change(searchUser(this)).keyup(function(e){
		var ev = e || window.event;
		if (ev.keyCode == 13 ||ev.keyCode == 32) {
			searchUser(this);
		}else if($(this).val()==''){
			$(this).parent().next().empty();
		}
	})
	
	$("#servicer-ul,#recommended-ul").on("click","li",function(){
		var $this = $(this);
		if($this.parent().attr('id')=="servicer-ul"){
			$("input[name='servicer_uid']").val($this.data('uid'));
			$("#servicer_uname").val($this.data('uname'));
		}else{
			$("input[name='recommend_uid']").val($this.data('uid'));
			$("input[name='recommend_uname']").val($this.data('uname'));
			$("input[name='recommend_mobile']").val($this.data('mobile'));
		}
		$this.parent().empty();
	});
	$(".contact-service-save").on('click',function(){
		var servicerUid = $("input[name='servicer_uid']").val();
		cAjax({
			url:"/cms/appUser/appUser/saveDing",
			data:{"uid":UID,"servicerUid":servicerUid},
			success:function(obj){
				var msg = "";
				if(obj.data == "1"){
					 msg = "修改服务岛丁成功";
				}else{
					msg = obj.msg;
				}
				greeting({
					msg:msg
				});
			}
		});
	});
	$("#country_code_name").on("change",function(){
		$("input[name='country_code']").val($("#country_code_name").val());
	})
		$("#country_code_show_name").on("change",function(){
		$("input[name='country_code_show']").val($("#country_code_show_name").val());
	})
});
